package br.unifacs.mda.plugin.main.gui.editors;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.ui.editors.text.TextEditor;
import org.eclipse.ui.ide.IDE;
import org.eclipse.ui.part.FileEditorInput;

import br.unifacs.mda.plugin.util.ExporterConstraint;

public class OCLEditor extends TextEditor {

	private String body;

	private IProject project;

	public OCLEditor() {
		super();
	}

	public void doSave(IProgressMonitor monitor) {
		super.doSave(monitor);

		try {
			String idConstraint = this.getConstraintID(((FileEditorInput) super
					.getEditorInput()).getFile().getLocation().toFile());

			this.project = ((FileEditorInput) super.getEditorInput()).getFile()
					.getProject();
			File file = this.project.getFile(
					"models/" + project.getName() + ".pim").getLocation()
					.toFile();

			ExporterConstraint.saveConstraint(file, idConstraint, this.body);

			this.refreshAll();
			this.saveProject();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (CoreException e) {
			e.printStackTrace();
		}
	}

	private String getConstraintID(File file) throws FileNotFoundException,
			IOException {
		String idConstraint = null;

		FileReader fr = new FileReader(file);
		BufferedReader input = new BufferedReader(fr);
		StringBuffer conteudo = new StringBuffer();
		String line;
		while ((line = input.readLine()) != null) {
			if (line.contains("@id")) {
				idConstraint = line.split("@id = ")[1];
			}
			conteudo.append(line + "\t\n");
		}
		this.body = conteudo.toString();
		input.close();
		return idConstraint;
	}

	private void refreshAll() throws CoreException {
		project.refreshLocal(IResource.DEPTH_INFINITE, null);
	}

	private void saveProject() {
		IResource[] resources = { this.project };
		IDE.saveAllEditors(resources, false);
	}
}
